package com.example.qaplatform.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.qaplatform.entity.UserEntity;
import com.example.qaplatform.repository.UserRepository;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        Map<String, Object> res = new HashMap<>();
        if (userRepository.findByUsername(username) != null) {
            res.put("success", false);
            res.put("msg", "用户名已存在");
            return res;
        }
        UserEntity user = new UserEntity();
        user.setUsername(username);
        user.setPassword(password); // 实际项目应加密
        user.setCreateTime(LocalDateTime.now());
        userRepository.save(user);
        res.put("success", true);
        return res;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");
        Map<String, Object> res = new HashMap<>();
        UserEntity user = userRepository.findByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            res.put("success", false);
            res.put("msg", "用户名或密码错误");
            return res;
        }
        res.put("success", true);
        res.put("userId", user.getId());
        return res;
    }
} 